<template>
<!-- 分页组件 -->
  <div class="pager-container" v-if="pageNumber > 1">
    <a @click="handleClick(1)" :class="{ disabled: current === 1 }"
      >|&lt;&lt;</a
    >
    <a @click="handleClick(current - 1)" :class="{ disabled: current === 1 }"
      >&lt;&lt;</a
    >
    <a
      @click="handleClick(v)"
      v-for="(v, i) in numbers"
      :key="i"
      :class="{ active: v === current }"
      >{{ v }}</a
    >
    <a
      @click="handleClick(current + 1)"
      :class="{ disabled: current === pageNumber }"
      >&gt;&gt;</a
    >
    <a
      @click="handleClick(pageNumber)"
      :class="{ disabled: current === pageNumber }"
      >&gt;&gt;|</a
    >
  </div>
</template>

<script>
export default {
  props: {
    // 当前页码
    current: {
      type: Number, //类型
      default: 1, // 默认项
    },
    // 总数据量
    total: {
      type: Number,
      default: 0,
    },
    // 页容量
    limit: {
      type: Number,
      default: 10,
    },
    // 可见页码数
    visibleNumber: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    // 总页数
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 得到最小的页码数
    vsiblMin() {
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min < 1) {
        min = 1;
      }
      return min;
    },
    // 得到最大的页码数
    vsiblMax() {
      let max = this.vsiblMin + this.visibleNumber - 1;
      if (max > this.pageNumber) {
        max = this.pageNumber;
      }
      return max;
    },
    numbers() {
      let num = [];
      for (let i = this.vsiblMin; i <= this.vsiblMax; i++) {
        num.push(i);
      }
      return num;
    },
  },
  methods: {
    handleClick(newpage) {
      if (newpage < 1) {
        newpage = 1;
      }
      if (newpage > this.pageNumber) {
        (newpage = this), pageNumber;
      }
      if (newpage === this.current) {
        return;
      }
      this.$emit("pagerChange", newpage);
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/style/global.css");
@import url("~@/style/var.less");
.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    // 悬停
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>